package com.hjt.gulimall.ware.config;

import com.hjt.gulimall.ware.constant.RabbitMqConstant;
import com.hjt.gulimall.ware.constant.WareConstant;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * RabbitMQ配置
 * @author:97007
 * @date:2021/10/8 16:03
 */
@Configuration
public class RabbitConfig {

    // 使用json序列化消息
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }


    @Bean
    public Queue stockDelayQueue() {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", "stock-event-exchange");
        arguments.put("x-dead-letter-routing-key", "stock.release"); // 指定路由键
        arguments.put("x-message-ttl", 120000);
        Queue queue = new Queue(RabbitMqConstant.STOCK_DELAY_QUEUE_NAME, true, false, false,arguments);
        return queue;
    }

    // 订单释放 的消息队列
    @Bean
    public Queue stockReleaseQueue() {
        Queue queue = new Queue(RabbitMqConstant.STOCK_RELEASE_QUEUE_NAME, true, false, false);
        return queue;
    }

    // 交换机
    @Bean
    public Exchange stockEventExchange() {
        return new TopicExchange(RabbitMqConstant.STOCK_EVENT_EXCHANGE_NAME, true, false);
    }

    // 绑定关系 stock-event-exchange ---(stock.locke)---> stock.delay.queue
    @Bean
    public Binding stockLockedBinding() {
        return new Binding(RabbitMqConstant.STOCK_DELAY_QUEUE_NAME, Binding.DestinationType.QUEUE,
                RabbitMqConstant.STOCK_EVENT_EXCHANGE_NAME,RabbitMqConstant.STOCK_LOCK_ROUTE_KEY,null);
    }
    // 绑定关系 stock-event-exchange ---(stock.release)---> stock.release.queue
    @Bean
    public Binding stockReleaseBinding() {
        return new Binding(RabbitMqConstant.STOCK_RELEASE_QUEUE_NAME, Binding.DestinationType.QUEUE,
                RabbitMqConstant.STOCK_EVENT_EXCHANGE_NAME,RabbitMqConstant.STOCK_RELEASE_ROUTE_KEY,null);
    }

}
